package gui.viewLattice;

import framework.classification.entities.ClAbstractEntity;
import framework.classification.library.IOCLassificationDirectory;
import gui.utils.JCoolButton;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;



import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PagePanel;





public class ViewPDF extends PagePanel{


	public String path;
	public Boolean ok;
	private PDFPage page;
	private ClAbstractEntity cl;
	

	
	public ViewPDF(ClAbstractEntity cl) throws IOException {

		super();
		this.cl = cl;
		ok = false;
		
		File file = new File(cl.getPathPDFLattice());
		if (!file.exists())
			cl.getAbstractClassfication().generateClEntityImage(cl,"",IOCLassificationDirectory.PDF);
		
		setSize(50,05);
		this.path = cl.getPathPDFLattice();
		
		updatePDF();
		
		this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			
		
	}

	public void updatePDF() throws IOException{

		if (!ok){
			File file = new File(path);
			while(!file.exists()){}
			RandomAccessFile raf = new RandomAccessFile(file, "r");
			FileChannel channel = raf.getChannel();
			ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
					0, channel.size());
			try{
				
				PDFFile pdffile = new PDFFile(buf);
				// show the first page
				 page = pdffile.getPage(0);
				showPage(page);
				ok = true;

			}
			catch(IOException io){
				updatePDF();
				ok =false;
			}
		}


	}
	
	public String getPath(){
		return path;
	}

	
	public ClAbstractEntity getClassification(){return cl;}

}
